package com.banfeiguanli.springboot.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.banfeiguanli.springboot.common.Constant;
import com.banfeiguanli.springboot.entity.BackAdmin;
import com.banfeiguanli.springboot.entity.ClassInfo;
import com.banfeiguanli.springboot.entity.User;
import com.banfeiguanli.springboot.exception.ServiceException;
import com.banfeiguanli.springboot.service.BackAdminService;
import com.banfeiguanli.springboot.service.ClassService;
import com.banfeiguanli.springboot.service.UserService;
import com.banfeiguanli.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Autowired
    private BackAdminService backAdminService;
    @Autowired
    private ClassService classService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        String password = "";
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //校验token是否为空
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(Constant.CODE_601, "登录失效，请重新登录");
        }
        //
        String tokenType = "";
        try {
            tokenType = TokenUtils.getTokenType(token);
        } catch (JWTDecodeException j) {
            throw new ServiceException(Constant.CODE_606, "token错误");
        }
        //
        if (tokenType.equals(Constant.USER)) {
            //从token中取出userId
            int userId;
            try {
                userId = TokenUtils.getIdByToken(token);
            } catch (JWTDecodeException j) {
                throw new ServiceException(Constant.CODE_602, "用户不存在，请重新登录");
            }
            //利于userId判断用户是否存在
            List<User> userList = userService.getUserInfoByUserId(userId);
            if (userList.isEmpty()) {
                throw new ServiceException(Constant.CODE_603, "用户不存在，请重新登录");
            }
            //检测用户是否被禁封
            if (userList.get(0).getIsBan().equals("是")) {
                throw new ServiceException(Constant.CODE_500, "用户已被禁封！");
            }
            //检测班级是否被禁封
            List<ClassInfo> classInfoList = classService.getClassInfo(userId);
            if (!classInfoList.isEmpty() && classInfoList.get(0).getIsBan().equals("是")) {
                throw new ServiceException(Constant.CODE_500, "班级已被禁封！");
            }
            password = userList.get(0).getUserPWD();
        } else if (tokenType.equals(Constant.ADMIN)) {
            //从token中取出userId
            int adminId;
            try {
                adminId = TokenUtils.getIdByToken(token);
            } catch (JWTDecodeException j) {
                throw new ServiceException(Constant.CODE_605, "管理员不存在，请重新登录");
            }
            //利于userId判断用户是否存在
            List<BackAdmin> backAdminList = backAdminService.getAdminInfoByAdminID(adminId);
            if (backAdminList.isEmpty()) {
                throw new ServiceException(Constant.CODE_607, "管理员不存在，请重新登录");
            }
            password = backAdminList.get(0).getAdminPWD();
        }
        else {
            throw new ServiceException(Constant.CODE_604, "token验证失败，请重新登录");
        }
        //验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(password)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constant.CODE_604, "token验证失败，请重新登录");
        }
        return true;
    }
}
